package com.deer.wms.base.system.util;

import com.alibaba.fastjson.JSONObject;
import com.deer.wms.base.system.aop.Dict;
import com.deer.wms.base.system.aop.NotMap;
import com.deer.wms.framework.web.service.DictService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @Author 申紫微
 * @Data 2020-08-19 09:28:58
 * @Version 1.0
 */
public class ParseDictUtils {

    protected static final Logger log = LoggerFactory.getLogger(ParseDictUtils.class);

    private static SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public static JSONObject parseDictText(Object obj) {

        if (Objects.isNull(obj)) {
            log.info("传入参数为空,无法进行字典转换");
            return new JSONObject();
        }

        DictService dictService = (DictService) SpringContextUtils.getBean("dict");

        ObjectMapper mapper = new ObjectMapper();

        String json = "{}";

        try {
            json = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("json解析失败" + e.getMessage(), e);
        }

        JSONObject item = JSONObject.parseObject(json);

        for (Field field : getAllFields(obj.getClass())) {
            //update-end--Author:scott  -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
            if (field.getAnnotation(Dict.class) != null) {
                String code = field.getAnnotation(Dict.class).dictType();
                String key = String.valueOf(item.get(field.getName()));
                String textValue = null;
                log.info(" 字典 key : " + key);

                if (StringUtils.isNotEmpty(key) && !"null".equals(key)) {
                    if (key.contains(",")) {
                        String[] strings = key.split(",");
                        StringBuffer textValues = new StringBuffer("");
                        for (String keys : strings) {
                            String value = dictService.getLabel(code, keys);
                            textValues.append(value).append(",");
                        }
                        textValue = textValues.toString().substring(0, textValues.toString().length() - 1);
                    } else {
                        textValue = dictService.getLabel(code, key);
                    }
                }
                log.info(" 字典Val : " + textValue);
                log.info(" __翻译字典字段__ " + field.getName() + "_dictText： " + textValue);
                item.put(field.getName() + "_dictText", textValue);
            }
        }
        return item;
    }

    /**
     * 获取累的属性
     *
     * @param clazz
     * @return java.util.List<java.lang.reflect.Field>
     * @author 申紫微
     * @date 9:48 2020/8/19
     **/
    public static List<Field> getClassFields(Class<?> clazz) {
        List<Field> clazzField = new ArrayList<Field>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(NotMap.class)) {
                continue;
            }
            if (field.isSynthetic()) {//如果类中字段为合成字段，剔除。
                continue;
            }
            clazzField.add(field);
        }
        return clazzField;
    }


    public static List<Field> getAllFields(Class clazz){
        List<Field> fieldList = new ArrayList<>();
        List<Field> clazzField = new ArrayList<Field>();
        while (clazz != null){
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        for (Field field : fieldList) {
            if (field.isAnnotationPresent(NotMap.class)) {
                continue;
            }
            if (field.isSynthetic()) {//如果类中字段为合成字段，剔除。
                continue;
            }
            clazzField.add(field);
        }
        return clazzField;
    }

}
